package com.tuyrt.`as`.proj.main.biz.goods

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView.LayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.launcher.ARouter
import com.tuyrt.`as`.proj.common.ui.component.HiAbsListFragment
import com.tuyrt.`as`.proj.main.fragment.home.GoodsItem
import com.tuyrt.`as`.proj.main.http.ApiFactory
import com.tuyrt.`as`.proj.main.http.api.GoodsApi
import com.tuyrt.`as`.proj.main.model.GoodsList
import com.tuyrt.`as`.proj.main.route.HiRoute
import com.tuyrt.hi.library.restful.HiCallback
import com.tuyrt.hi.library.restful.HiResponse
import com.tuyrt.hi.ui.item.HiDataItem

/**
 * author: Administrator on 2021/7/8.
 * desc:
 */
class GoodsListFragment : HiAbsListFragment() {

    companion object {
        fun newInstance(categoryId: String, subcategoryId: String): GoodsListFragment {
            val args = Bundle()
            args.putString("categoryId", categoryId)
            args.putString("subcategoryId", subcategoryId)
            val fragment = GoodsListFragment()
            fragment.arguments = args
            return fragment
        }
    }

    @JvmField
    @Autowired
    var categoryId: String = ""

    @JvmField
    @Autowired
    var subcategoryId: String = ""

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        HiRoute.inject(this)
        enableLoadMore { loadData() }
        loadData()
    }

    override fun onRefresh() {
        super.onRefresh()
        loadData()
    }


    override fun createLayoutManager(): LayoutManager {
        return GridLayoutManager(context, 2)
    }

    private fun loadData() {
        ApiFactory.create(GoodsApi::class.java)
            .queryCategoryGoodsList(categoryId, subcategoryId, pageIndex, 10)
            .enqueue(object : HiCallback<GoodsList> {
                override fun onSuccess(response: HiResponse<GoodsList>) {
                    if (response.successful() && response.data != null) {
                        onQueryCategoryGoodsListSuccess(response.data!!)
                    } else {
                        finishRefresh(null)
                    }
                }

                override fun onFailed(throwable: Throwable) {
                    finishRefresh(null)
                }
            })
    }

    private fun onQueryCategoryGoodsListSuccess(data: GoodsList) {
        val dataItems = mutableListOf<GoodsItem>()
        for (goodsModel in data.list) {
            val goodsItem = GoodsItem(goodsModel, false)
            dataItems.add(goodsItem)
        }
        finishRefresh(dataItems)
    }

}